package com.ican.study2.security;

import java.util.HashSet;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.ican.study2.biz.demo.domain.system.user.Resources;
import com.ican.study2.biz.demo.domain.system.user.User;
import com.ican.study2.biz.demo.service.system.user.UserService;

public class MyUserDetailServiceImpl implements UserDetailsService {
    
    private UserService userService;
    
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findUserByName(username);
        if(user == null) {
            throw new UsernameNotFoundException(username);
        }
        Set<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);
        return new org.springframework.security.core.userdetails.User(
                user.getName(), user.getPassword(), grantedAuths);
    }
    
    //取得用户的权限
    private Set<GrantedAuthority> obtionGrantedAuthorities(User user) {
        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
        for(Resources res : user.getResources()) {
            authSet.add(new SimpleGrantedAuthority(res.getName()));
        }
        return authSet;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}